package com.example.bpmn.listener;

import com.example.bpmn.event.ProcessEvent;
import com.example.bpmn.service.ProcessEventPublisher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class CamundaProcessListener implements ExecutionListener {
    
    private final ProcessEventPublisher eventPublisher;

    @Override
    public void notify(DelegateExecution execution) throws Exception {
        String eventName = execution.getEventName();
        String processInstanceId = execution.getProcessInstanceId();
        String businessKey = execution.getBusinessKey();
        
        log.info("流程事件触发: eventName={}, processInstanceId={}, businessKey={}", 
            eventName, processInstanceId, businessKey);

        // 根据不同事件类型处理
        switch (eventName) {
            case ExecutionListener.EVENTNAME_START:
                handleProcessStart(execution);
                break;
            case ExecutionListener.EVENTNAME_END:
                handleProcessEnd(execution);
                break;
            case ExecutionListener.EVENTNAME_TAKE:
                handleProcessTransition(execution);
                break;
            default:
                log.warn("未知的事件类型: {}", eventName);
        }

        // 发布事件到消息队列
        eventPublisher.publishEvent(eventName, businessKey, processInstanceId);
    }

    private void handleProcessStart(DelegateExecution execution) {
        log.info("流程开始: processDefinitionId={}", 
            execution.getProcessDefinitionId());
    }

    private void handleProcessEnd(DelegateExecution execution) {
        log.info("流程结束: processDefinitionId={}", 
            execution.getProcessDefinitionId());
    }

    private void handleProcessTransition(DelegateExecution execution) {
        log.info("流程流转: currentActivityId={}, targetActivityId={}", 
            execution.getCurrentActivityId(),
            execution.getCurrentTransitionId());
    }
} 